(function() {
    'use strict';
    /**
     * @ngdoc function
     * @name webApp.controller:RoomCtrl
     * @description
     * # RoomsCtrl
     * Controller of the webApp
     */
    angular.module('webApp')
        .controller('RoomsCtrl', RoomsCtrl);

    RoomsCtrl.$inject = ['$scope', 'dataService', '$location', '$state', 'helper', '$timeout', '$rootScope'];

    function RoomsCtrl($scope, dataService, $location, $state, helper, $timeout, $rootScope) {
        $scope.listAction = function() {
            $scope.pageSize = 10;
            $scope.getRoomList(1);
            $scope.$on('event:up-store-id', function() {
                $scope.store_id = $rootScope.store_id
                $scope.getRoomList(1);
            });
        }

        //获取房间列表
        $scope.getRoomList = function(pageNo) {
            $scope.pageNo = pageNo ? pageNo : "1";
            var query = {
                "content": {
                    page_no: $scope.pageNo,
                    page_size: $scope.pageSize,
                    store_id: $rootScope.store_id,
                }
            };

            dataService.roomsGet(query).then(function(list) {
                if (list) {
                    $scope.room_list = list.room_list;
                    $scope.total_count = list.total_count;
                }
            });
        }

        //添加数据 初始化
        $scope.addAction = function() {
            $scope.$on('event:up-tore-id', function() {
                $scope.store_id = $rootScope.store_id
            });

            if (!$scope.store_id) {
                return helper.myAlert("非法门店id", "#/rooms/list");
            }

            $scope.rooms = {};

            var room_id = $location.search().room_id;
            if (room_id) {
                $scope.getRoomOne(room_id);
            } else {
                //初始化值
                $scope.rooms.name = "标准间";
                $scope.rooms.img = "";
                $scope.rooms.store_id = parseInt($scope.store_id);
                $scope.rooms.room_num = 10;
                $scope.rooms.max_booking_days = 7;
                $scope.rooms.on_shelves = 1;
                $scope.rooms.description = "预约房间";
                // $scope.rooms.price = 1;
                $scope.rooms.remark = "";

                $scope.rooms.weekdays = {
                    "0": { "son_data": [] },
                    "1": { "son_data": [] },
                    "2": { "son_data": [] },
                    "3": { "son_data": [] },
                    "4": { "son_data": [] },
                    "5": { "son_data": [] },
                    "6": { "son_data": [] }
                };

                // $scope.rooms.special_time = [];
            }
        }

        //增加特殊时间
        // $scope.addSpecialTime = function() {
        //     $scope.rooms.special_time.push({ "special_time": "", "price": 1, "on_shelves": 1 });
        // }

        /*
         * 选择周几，增加房间规格
         */
        $scope.addWeekday = function(week) {
            $scope.rooms.weekdays[week].son_data.push({ "tag_id": 0, "tag_name": "", "price": 1, "on_shelves": 1 });
        }

        //设置时间段
        $scope.addTag = function(week) {
            $scope.rooms.weekdays[week].son_data.push({ "tag_id": 0, "tag_name": "", "price": 1, "on_shelves": 1 });
        }

        //选中周几 添加时间段
        $scope.isChecked = function($event, flag) {
            var status = $event.currentTarget.checked;
            if (status) {
                $scope.addWeekday(flag);
            } else {
                $scope.rooms.weekdays[flag].son_data = [];
            }
        }

        //删除时间段
        $scope.tagDelete = function(room_id, sku_id, flag, index) {
            var data = {};
            data.content = {};

            if (room_id) {
                data.content.room_id = room_id;
            }

            if (sku_id) {
                data.content.sku_id = sku_id;
            } else {
                $timeout(function() {
                    $scope.rooms.weekdays[flag].son_data.splice(index, 1);
                });

                return false;
            }

            dataService.roomskusDelete(data).then(function(result) {
                if (result.Msg == "ok") {
                    helper.myAlert("success");
                    $scope.getRoomOne(room_id);
                } else {
                    helper.myAlert("error：" + result.Msg);
                    return false;
                }
            });
        }

        $scope.getRoomOne = function(id) {
            var query = {
                "content": {
                    "pageNo": 1,
                    "pageSize": 10,
                    "store_id": $rootScope.store_id,
                    "rooms_id": id
                }
            };
            dataService.roomsGet(query).then(function(one) {
                if (one) {
                    $scope.rooms = one.room_list[0];
                    $scope.rooms.description = json2html(JSON.parse($scope.rooms.description));

                    //查询之后初始化sku数据
                    for (var i = 0; i < 7; i++) {
                        if (!$scope.rooms.sku[i]) {
                            $scope.rooms.sku[i] = { "son_data": [] };
                        }
                    }
                    $scope.rooms.weekdays = $scope.rooms.sku;
                } else {
                    helper.myAlert("No data found", null, null, function() {
                        $state.go("rooms.list");
                    });
                }
            });
        }

        //点击保存，新增房间
        $scope.roomsAdd = function() {
            var room_id = $location.search().room_id;

            var sku = $scope.rooms.weekdays;
            $scope.rooms.newSku = {};
            //过滤sku的无效数据
            for (var i in sku) {
                if (sku[i].son_data.length) {
                    $scope.rooms.newSku[i] = sku[i];
                }
            }

            if (JSON.stringify($scope.rooms.newSku) == '{}') {
                helper.myAlert("error：没有设置sku，不能保存商品");
                return false;
            }

            for (var i in $scope.rooms.newSku) {
                var son_data = $scope.rooms.newSku[i].son_data;
                for (var j in son_data) {
                    if (!son_data[j].tag_id || !son_data[j].tag_name) {
                        helper.myAlert("sku信息填写不完整，无法保存");
                        return false;
                    }
                }
            }

            if (room_id) {
                dataService.roomsUpdate($scope.rooms).then(function(result) {
                    if (result.Msg == "ok") {
                        helper.myAlert("修改成功", "#/rooms/list");
                    } else {
                        helper.myAlert("error：" + result.Msg);
                        return false;
                    }
                });
            } else {
                dataService.roomsAdd($scope.rooms).then(function(result) {
                    if (result.Msg == "ok") {
                        helper.myAlert("保存成功", "#/rooms/list");
                    } else {
                        helper.myAlert("error：" + result.Msg);
                        return false;
                    }
                });
            }
        }

        //处理上传图片
        $scope.HandleImage = function(itemsData) {
            var isitemsData = clone(itemsData);
            try {
                isitemsData.description = JSON.stringify(html2json(isitemsData.description))
            } catch (e) {
                isitemsData.description = "";
            }
            var pic = 0;
            _.map(isitemsData.skus, function(sku, ke) {
                if (sku.status_id == 1) {
                    if (!pic) {
                        pic = sku.sku_price;
                    }
                    if (sku.sku_price < pic) {
                        pic = sku.sku_price;
                    }
                }
            });
            isitemsData.price = pic;
            return isitemsData;
        }

        //订单列表
        $scope.orderlistAction = function() {
            $scope.pageSize = 10;

            $scope.chosedStatus = "S_ORDER_WAIT_CONFIRM";
            $scope.getorderList(1);
            $scope.$on('event:up-store-id', function() {
                $scope.store_id = $rootScope.store_id;
                $scope.getorderList(1);
            });
        }

        $scope.getorderList = function(pageNo) {
            $scope.pageNo = pageNo ? pageNo : "1";
            var query = {
                "content": {
                    page_no: $scope.pageNo,
                    page_size: $scope.pageSize,
                    store_id: $rootScope.store_id,
                }
            };

            if ($scope.room_order_id) {
                query.content.order_id = $scope.order_id;
            }
            if ($scope.start_created && $scope.end_created) {
                query.content.start_created = $scope.start_created;
                query.content.end_created = $scope.end_created;
            }

            if ($scope.chosedStatus && $scope.chosedStatus !== "All") {
                query.content.status = $scope.chosedStatus;
            }

            dataService.roomsOrderGet(query).then(function(list) {
                if (list) {
                    $scope.order_list = list.order_list;
                    $scope.order_count = list.order_count;
                }
            });
        }

        //订单详情
        $scope.orderinfoAction = function() {
            var id = $location.search().room_order_id;

            $scope.orderid = id;
            if (id) {
                $scope.ordergetone($scope.orderid);
            } else {
                helper.myAlert("No data found", null, null, function() {
                    $state.go("rooms.orderlist");
                });
            }
        }

        $scope.ordergetone = function(id) {
            var query = {
                "content": {
                    store_id: $rootScope.store_id,
                    room_order_id: id
                }
            };

            dataService.roomsOrderGet(query).then(function(list) {
                if (list) {
                    $scope.order = list.order_list[0];
                }
            });
        }

        //订单修改 确认订单
        $scope.roomsOrderUpdate = function(room_order_id, $event) {
            helper.myConfirm('确认订单？', function() {
                var query = {
                    "content": {
                        "store_id": $rootScope.store_id,
                        "room_order_id": room_order_id,
                        "confirm": 1
                    }
                };

                dataService.roomsOrderUpdate(query).then(function(result) {
                    if (result.Msg == "ok") {
                        helper.myAlert("success", null, null, function() {
                            $state.go("rooms.orderlist", null, {
                                reload: true
                            });
                        });
                    } else {
                        helper.myAlert("error：" + result.Msg);
                        return false;
                    }
                });
            });
        }
    }
})();